package services

import (
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/jinzhu/gorm"
	"go_motor_catalog/dao"
	"go_motor_catalog/util"
	"net/url"
	"strings"
)

const getSuzukiModelUrl = "https://www1.suzuki.co.jp/motor/support/owners_manual/dl/"

const getSuzukiBaseUrl = "https://www1.suzuki.co.jp"

type SuzukiOm struct {
}

type SuzukiOmRes struct {
	ModelName       string
	ModelYear       string
	CatalogUrl      string
	CatalogShareUrl string
	Desc            string
}

func NewSuzukiOm() *SuzukiOm {
	return &SuzukiOm{}
}

func (s *SuzukiOm) getModel() []map[string]string {
	res := make([]map[string]string, 0)
	ccList := []string{"index.html?bikedisp=6", "index.html?bikedisp=5", "index.html?bikedisp=4", "index.html?bikedisp=3", "index.html?bikedisp=2", "index.html?bikedisp=1"}
	for i := range ccList {
		modelUrl := getSuzukiModelUrl + ccList[i]
		response := util.NewHttpUtil().GetRes(modelUrl)
		modelResponse, err := goquery.NewDocumentFromResponse(response)
		if err != nil {
			fmt.Println("获取model列表失败", err)
			return res
		}
		nodes := modelResponse.Find(".modelname").Find("option").Nodes
		for n := range nodes {
			if n == 0 {
				continue
			}
			attr := nodes[n].Attr
			for a := range attr {
				if attr[a].Key == "value" {
					urlSplit := strings.Split(attr[a].Val, "=")
					parse := url.QueryEscape(urlSplit[len(urlSplit)-1])
					parse = strings.ReplaceAll(parse, "+", "%20")
					parse = strings.ReplaceAll(parse, "/", "%2F")
					urlSplit[len(urlSplit)-1] = parse
					var urlLastParam = ""
					for u := range urlSplit {
						if u == 0 {
							urlLastParam += urlSplit[u]
						} else {
							urlLastParam += "=" + urlSplit[u]
						}
					}
					modelUrl := fmt.Sprintf("%v%v", getSuzukiModelUrl, urlLastParam)
					modelSplit := strings.Split(attr[a].Val, "=")
					modelName := modelSplit[len(modelSplit)-1]
					res = append(res, map[string]string{
						"modelName": modelName, "modelUrl": modelUrl,
					})
				}

			}
		}
	}
	return res
}

func (s *SuzukiOm) getYear(getYearUrl string) []map[string]string {
	res := make([]map[string]string, 0)
	response := util.NewHttpUtil().GetRes(getYearUrl)
	modelResponse, err := goquery.NewDocumentFromResponse(response)
	if err != nil {
		fmt.Println("获取year列表失败", err)
		return res
	}
	nodes := modelResponse.Find(".modelyear").Find("option").Nodes
	for n := range nodes {
		if n == 0 {
			continue
		}
		attr := nodes[n].Attr
		for a := range attr {
			if attr[a].Key == "value" {
				yearUrl := fmt.Sprintf("%v%v", getSuzukiModelUrl, attr[a].Val)
				yearSplit := strings.Split(yearUrl, "=")
				yearName := yearSplit[len(yearSplit)-1]
				res = append(res, map[string]string{
					"yearName": yearName, "yearUrl": yearUrl,
				})
			}

		}
	}
	return res
}

func (s *SuzukiOm) getCatalog(getCatalogUrl string) string {
	getCatalogUrlSplit := strings.Split(getCatalogUrl, "?")
	getCatalogUrlSplitLast := getCatalogUrlSplit[1]
	urlSplit := strings.Split(getCatalogUrlSplitLast, "&")
	modelNameUrl := strings.Split(urlSplit[1], "=")[1]
	parse := url.QueryEscape(modelNameUrl)
	parse = strings.ReplaceAll(parse, "+", "%20")
	parse = strings.ReplaceAll(parse, "/", "%2F")
	modelNameUrl = "modelname=" + parse
	var urlLastParam = ""
	for u := range urlSplit {
		if u == 0 {
			urlLastParam += urlSplit[u]
		} else if u == 1 {
			urlLastParam += "&" + modelNameUrl
		} else {
			urlLastParam += "&" + urlSplit[u]
		}
	}
	var getCatalogUrlRes = getCatalogUrlSplit[0] + "?" + urlLastParam
	response := util.NewHttpUtil().GetRes(getCatalogUrlRes)
	modelResponse, err := goquery.NewDocumentFromResponse(response)
	if err != nil {
		fmt.Println("获取catalog列表失败", err)
		return ""
	}
	val, exists := modelResponse.Find(".parts_catalog_search_result_block").First().Find("a").Attr("href")
	if !exists {
		return ""
	}
	return fmt.Sprintf("%v%v", getSuzukiBaseUrl, val)
}

func (s *SuzukiOm) CrawData(db *gorm.DB) {
	omDao := dao.NewManualModelOmDao(db)
	catalogDao := dao.NewManualCatalogOmDao(db)
	models := s.getModel()
	for i := range models {
		model := models[i]
		modelName := model["modelName"]
		modelUrl := model["modelUrl"]
		years := s.getYear(modelUrl)
		for y := range years {
			year := years[y]
			yearName := year["yearName"]
			yearUrl := year["yearUrl"]
			catalogUrl := s.getCatalog(yearUrl)
			if catalogUrl == "" {
				fmt.Println(modelName, "-", yearName, "-获取失败")
				continue
			}
			fmt.Println(modelName, "-", yearName, "-", catalogUrl)
			modelBean := &dao.ManualModelOm{
				ModelName:       modelName,
				ModelNameDetail: "",
				ModelYear:       yearName,
				BrandId:         2,
			}
			catalogBean := &dao.ManualCatalogOm{
				CatalogUrl: catalogUrl,
			}
			omDao.CreateManualModelOm(modelBean)
			if modelBean.Id == 0 {
				continue
			}
			catalogBean.ModelId = modelBean.Id
			catalogDao.CreateManualCatalogOm(catalogBean)
			fmt.Println(modelName, "-", yearName, "-successfull")
		}
	}
}
